/*
 * @Date: 2023-07-14 09:12:34
 * @LastEditors: lyx
 * @LastEditTime: 2023-11-14 14:21:05
 * @FilePath: \sup-mimi-program-server\src\posts\posts.service.ts
 * @Description:
 */
import { Injectable } from '@nestjs/common';
import { ReturnModelType } from '@typegoose/typegoose';
import { InjectModel } from 'nestjs-typegoose/dist/typegoose.decorators';
import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';
import { Post as PostSchema } from './entities/post.entity';
import { get } from 'lodash';
import { defaultPaginate } from 'utils/mongo-crud/crud-config';
import { CrudDto } from 'utils/mongo-crud/crud.dto';
import { getMongoQueryParams, isQueryAll } from 'utils/mongo-crud';

@Injectable()
export class PostsService {
  constructor(
    @InjectModel(PostSchema)
    private readonly postModel: ReturnModelType<typeof PostSchema>,
  ) {}
  async create(createPostDto: CreatePostDto) {
    const res = await this.postModel.create(createPostDto);
    return res;
  }

  async find(query: ICrudBody = {}) {
    const { where, page, skip, limit, sort, populate, collation, total } =
      await getMongoQueryParams(query, this.postModel);

    const find = async () => {
      const data = await this.postModel
        .find()
        .where(where)
        .skip(skip)
        .limit(limit)
        .sort(sort)
        .populate(populate)
        .collation(collation);

      return {
        [defaultPaginate.records]: data,
        [defaultPaginate.current]: page,
        [defaultPaginate.pages]: Math.ceil(total / limit),
        [defaultPaginate.size]: limit,
        [defaultPaginate.total]: total,
      };
    };
    return find();
  }

  async findAll() {
    return await this.postModel.find();
  }

  async findOne(id: string) {
    return await this.postModel.findById(id);
  }

  async update(id: string, updatePostDto: UpdatePostDto) {
    return await this.postModel.findByIdAndUpdate(id, updatePostDto);
  }

  async remove(id: string) {
    return await this.postModel.findByIdAndRemove(id);
  }
}
